<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String cat=request.getParameter("category");
	String title=null;
	if(cat.equalsIgnoreCase("1")){
		title="FITX價格圖";
	}else if(cat.equalsIgnoreCase("2")){
		title="0050成交價格圖";
	}else if(cat.equalsIgnoreCase("3")){
		title="FITX 50 價格圖";
	}
	
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache"> 
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache"> 
<META HTTP-EQUIV="Expires" CONTENT="0"> 
<!--[if lt IE 9]><script language="javascript" type="text/javascript" src="../js/excanvas.js"></script><![endif]-->
<link rel="stylesheet" href="../css/jquery.jqplot.css">
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script type="text/javascript" src="../js/jquery.jqplot.js"></script>
<script type="text/javascript" src="../js/jqplot.canvasAxisTickRenderer.js"></script>
<script type="text/javascript" src="../js/jqplot.canvasTextRenderer.js"></script>
<script type="text/javascript" src="../js/jqplot.barRenderer.js"></script>
<script type="text/javascript" src="../js/jqplot.categoryAxisRenderer.js"></script>
<script type="text/javascript" src="../js/jqplot.highlighter.min.js"></script>
<script type="text/javascript" src="../js/jqplot.cursor.min.js"></script>
<script type="text/javascript" src="../js/jquery.blockUI.js"></script>
<title><%=title%> VS ${date}命中率分Ｋ顯示e</title>
</head>
<style type="text/css">
html, body{
	background-color: white;
}
#data{
	margin: auto;
	margin-left:0.5em;
	margin-bottom: 10px;
	/*width: 200px;*/
}

#data span{
	font-size: 1em;
	font-weight:bold;
	color:rgb(70%,50%,100%);
}

#tooltip span{
	font-size: 0.6em;
	font-weight:normal;
	color:rgb(50%,50%,100%);
}

#mainTable{
	border: 1px solid #98bf21;
}

#mainTable td,#mainTable th{
	border: 1px solid #98bf21;
}

.dataTable{
	font: 10px;
}

.dataTable th,.dataTable td{
	border: 1px solid #98bf21;
	color: blue;
	text-align: center;
	font-size: 10px;
}

#link {
	margin-top: 0.2em;
	margin-bottom: 0.2em;
}

#link span{
	font-size:0.8em;
	padding-right: 0.8em;
}

#searchDiv span{
	font-size:0.8em;
	color:rgb(20%,20%,100%);
}
</style>
<script type="text/javascript">
	
	var lastTick='';
	var debug=false;
	$(document).ready(function(){
		
		$('#main').css({'width':$(window).width()-10});
		$("#searchBtn").click(function(){
			findTick($("#tickVal").val());
		});
		$("#getBackTest").click(function(){
			getBackTest();
		});
		$("#closeBtn").click(function(){
			 $.unblockUI(); 
	         return false; 
		});
		$("#allBtn").click(function(){
			$("#backTestData").select();
			 $.copy($("#backTestData").val());
		});
		//a1:平手, a2:買方中, a3:賣方中, a4:失敗
		var line1 = [${a2}];
	    var line2 = [${a3}];
	    var line3 =[${a4}];
	    var line4 = [${a1}];
	    var line5 = [${a5}];
	    var interval=1000;
	  	//if(<%=cat%>==1){
	  	//	interval=1000;
	  	//}
	  	
	    plot = $.jqplot('chart', [line1, line2, line3,line4,line5], {
	    	 stackSeries: true,
	         legend: {
	             //show: true,
	             //location: 'e'
	         },

	         title: '<%=title%> VS ${date}命中率分Ｋ顯示',

	         series: [
			 {
				color: '#FF3300',
				label: '命中買${bCnt}',
				renderer:$.jqplot.BarRenderer,
				rendererOptions: {
	                barWidth:4,
	                shadowOffset:0 
	             }
			 },
			 {
				 color: '#00FF00',
				 label: '命中賣${sCnt}',
				 renderer:$.jqplot.BarRenderer,
				 rendererOptions: {
					barWidth:4,
	                shadowOffset:0 
	             }
			 },

			 {
				 color: '#FF9900',
				 label: '未命中${o3}',
				 renderer:$.jqplot.BarRenderer,
				 rendererOptions: {
	                 barWidth:4,
	                 shadowOffset:0 
	             }
			 },
			 {
				 color: '#505050 ',
				 label: '持平${o1}',
				 renderer:$.jqplot.BarRenderer,
				 rendererOptions: {
	                 barWidth:4,
	                 shadowOffset:0 
	             }
			 },
			 {
				 color: '#0066FF',
				 yaxis:'y2axis',
				 showMarker:false,
				 label: '目標股價',
				 disableStack:true, 
				 fill:false
			 }],
	         axes: {
	             xaxis: {
	                 //renderer: $.jqplot.CategoryAxisRenderer
	               	 min: 0,
	               	 max:270,
	                 tickInterval : 5,
	                 tickOptions:{
	                     formatString:'%d'
	                 }
	             },
	             yaxis: {
	            	 tickInterval : interval,
	            	 tickOptions:{
	                     //formatString:'權重比例:%d%',
	                     formatter: function (format, val){
	                    	 return '權重比例:'+val/100+"%";
	                     }
	                 } 
	             },
	             y2axis: {
	            	 autoscale:true,
	                 tickInterval : 50,
	                 tickOptions:{
	                	 showGridline:false,
	                	 formatString:'股價 :%d'
	                 }
	             }
	         },
	         highlighter: {
	        	 show:true, 
	        	 tooltipAxes: 'xy',
	        	 formatString:'<table class="jqplot-highlighter"><tr><td>T: %s</td></tr><tr><td>%s</td></tr></table>'
	        },
	        cursor: {
	            show: true,
	            showTooltip :false,
	            //followMouse:true,
	            tooltipFormatString:'%s, tick: %d, %s',
	            //tooltipFormatString:'%s,%d,%s',
	            //tooltipLocation:'ne',
	        	intersectionThreshold:1,
	            showVerticalLine :true,
	            showHorizontalLine :true,
	            showTooltipUnitPosition:false,
	            showTooltipDataPosition:true,
	            tooltipAxisGroups:[['xaxis','y2axis']],
	            zoom:false
	        }
	     });
	    $('#chart').bind('jqplotMouseMove',handleMouseMove); 
	    //$('#chart').bind('jqplotMouseLeave',handleMouseLeave);
	    $('#chart').bind('jqplotClick',handleClick);
	    $("#type0").css({"color":plot.series[0].color}).text(plot.series[0].label);
	    $("#type1").css({"color":plot.series[1].color}).text(plot.series[1].label);
	    $("#type2").css({"color":plot.series[2].color}).text(plot.series[2].label);
	    $("#type3").css({"color":plot.series[3].color}).text(plot.series[3].label);
	});
	
    function handleClick(ev, gridpos, datapos, neighbor, plot) {
        if (neighbor) {
        	findTick(neighbor.data[0]);
        }
    }
        
    function findTick(tick){
    	$("#tickVal").val(tick);
    	if(tick&&lastTick!=tick){
    		$('#log').empty();
    		$('#mainTable').block({ message: '<img src="../images/loader2.gif" />' });
    		//setTimeout(function(){ $('#mainTable').unblock();}, 2000); 
			lastTick=tick;
			$('.dataTable tbody').empty();
			$.ajax({
				type: "POST",
				url: "getTickData",
				data: "date=${date}&tick="+lastTick+"&category=<%=cat%>",
				dataType: "json",
				error: function(jqXHR, textStatus, errorThrown){
					$('#log').html("資料取得錯誤! <br/>:njqXHR : "+jqXHR+"<br/>textStatus : "+textStatus+"<br/>errorThrown : "+errorThrown);
				},
				success: function(data){	
					var s='';
					var a0=0,a1=0,a2=0,a3=0;
					var w0=0,w1=0,w2=0,w3=0;
					$('.dataTable tbody').empty();
					for(i=0;i<data.length;i++){
						var stock=data[i].stockId;
						var time1=data[i].time1;
						var dprice=data[i].dprice;
						var bsum=parseInt(data[i].bsum);
						var ssum=parseInt(data[i].ssum);
						var avg=parseInt(data[i].avg);
						var tag=data[i].tag;
						var ww=parseInt(data[i].weight);
						s+=(stock+', '+dprice+', '+bsum+', '+ssum+', '+avg+', '+tag+'<br/>');
						if(tag=='2'){
							a2++;
							w2=w2+ww;
							$('#id2 tbody').append("<tr><td>"+stock+"</td><td>"+time1+"</td><td>"+dprice+"</td><td>"+bsum+"</td><td>"+ssum+"</td><td>"+avg+"</td></tr>");
						}
						if(tag=='1'){
							//if(bsum>=ssum||bsum>=avg){
							if(bsum>=ssum){
								a0++;
								w0=w0+ww;
								$('#id0 tbody').append("<tr><td>"+stock+"</td><td>"+time1+"</td><td>"+dprice+"</td><td>"+bsum+"</td><td>"+ssum+"</td><td>"+avg+"</td></tr>");
							}else{
								a1++;
								w1=w1+ww;
								$('#id1 tbody').append("<tr><td>"+stock+"</td><td>"+time1+"</td><td>"+dprice+"</td><td>"+bsum+"</td><td>"+ssum+"</td><td>"+avg+"</td></tr>");
							}
							
						}
						if(tag=='0'){
							a3++;
							w3=w3+ww;
							$('#id3 tbody').append("<tr><td>"+stock+"</td><td>"+time1+"</td><td>"+dprice+"</td><td>"+bsum+"</td><td>"+ssum+"</td><td>"+avg+"</td></tr>");
						}
					}
					$('#id0 tbody td').css({"color":plot.series[0].color});
					$('#id1 tbody td').css({"color":plot.series[1].color});
					$('#id2 tbody td').css({"color":plot.series[2].color});
					$('#id3 tbody td').css({"color":plot.series[3].color});
					$("#type0").text(plot.series[0].label+" (筆數:"+a0+"), 權重:"+w0/100+"%");
					$("#type1").text(plot.series[1].label+" (筆數:"+a1+"), 權重:"+w1/100+"%");
					$("#type2").text(plot.series[2].label+" (筆數:"+a2+"), 權重:"+w2/100+"%");
					$("#type3").text(plot.series[3].label+" (筆數:"+a3+"), 權重:"+w3/100+"%");
					if(debug){
						$('#log').html(s);
					}
				 },
				 complete:function(jqXHR,textStatus){
					 $('#mainTable').unblock();
				 }
			});		
		}
    }
	
	function handleMouseLeave(ev, gridpos, datapos, neighbor, plot) {
		$('#tooltip').empty();
    	$('#tooltip').html('<span>x:0, y:0 &nbsp;|&nbsp;x:0, y:0 &nbsp;|&nbsp;x:0, y:0 &nbsp;|&nbsp;x:0, y:0 &nbsp;|&nbsp;x:0, y:0</span>');
	}
	
	function handleMouseMove(ev, gridpos, datapos, neighbor, plot1){
		$('#tooltip').empty();
		var c = plot.plugins.cursor;
		var s = '';
		var addbr = false;
	    var series = plot.series; 
	    var ret = getIntersectingPoints(plot, gridpos.x, gridpos.y);
	 	for (var i = 0; i< series.length; i++) {
			var idx = series[i].index;
			var label = series[i].label.toString();
			var color = series[i].color;
		   	var cellid = $.inArray(idx, ret.indices);
		    var sx = undefined;
			var sy = undefined;
			if (cellid != -1) {
				s+='<span style="color:'+color+';">';
				var data = ret.data[cellid].data;
		     	var xf = series[i]._xaxis._ticks[0].formatter;
		     	var yf = series[i]._yaxis._ticks[0].formatter;
		     	var xfstr = series[i]._xaxis._ticks[0].formatString;
		    	var yfstr = series[i]._yaxis._ticks[0].formatString;
		     	sx = xf(xfstr, data[0]);
		     	sy = yf(yfstr, data[1]);
				s += $.jqplot.sprintf(c.tooltipFormatString, label, sx, sy);
			  	s+='&nbsp;|&nbsp;</span>';
		 	}
	    }
	    $('#tooltip').html(s);
	}

	function getIntersectingPoints(plot, x, y) {
        var ret = {indices:[], data:[]};
        var s, i, d0, d, j, r, p;
        var threshold;
        var c = plot.plugins.cursor;
        for (var i=0; i<plot.series.length; i++) {
            s = plot.series[i];
            r = s.renderer;
            if (s.show) {
                threshold = c.intersectionThreshold;
                if (s.showMarker) {
                    threshold += s.markerRenderer.size/2;
                }
                for (var j=0; j<s.gridData.length; j++) {
                    p = s.gridData[j];
                    // check vertical line
                    if (c.showVerticalLine) {
                        if (Math.abs(x-p[0]) <= threshold) {
                            ret.indices.push(i);
                            ret.data.push({seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]});
                        }
                    }
                } 
            }
        }
        return ret;
    }
	
	function getBackTest(){
		$.blockUI({ message: '<h1><img src="../images/loader2.gif" /></h1>' });
		$("#backTestData").val("");
		$.ajax({
			type: "POST",
			url: "getBackTest",
			data: "date=${date}&category=<%=cat%>",
			error: function(jqXHR, textStatus, errorThrown){
				$("#backTestData").val("資料取得錯誤! \n: jqXHR : "+jqXHR+"\ntextStatus : "+textStatus+"\nerrorThrown : "+errorThrown);
				$("#backTestData").css({'width':380,'height':350});
				$.blockUI({ message: $("#backTestDiv"),
					css:{'width':400,
						 'height':400,
						 top:($(window).height() - 400) /2 + 'px',
						 left: ($(window).width() - 400) /2 + 'px',
						 overflow: 'auto'
						 }
				});
			},
			success: function(data){
				$("#backTestData").val(data);
				$("#backTestData").css({'width':$(window).width()-520,'height':$(window).height()-120});
				$.blockUI({ message: $("#backTestDiv"),
					css:{'width':$(window).width()-500,
						 'height':$(window).height()-50,
						 top:($(window).height() - ($(window).height()-50)) /2 + 'px',
						 left: ($(window).width() - ($(window).width()-500)) /2 + 'px',
						 overflow: 'auto'}
				});
			}
		});		
	}
	
	function goTo(url){
		$.blockUI({message: '<img src="../images/loader2.gif" />'});
		window.location=url;
	}	
	
</script>
<body>
<div id="data">
	<span>
		資訊 : 
	</span>
	<div id="tooltip">
		<span>
		x:0, y: 0 &nbsp;&nbsp;|&nbsp;&nbsp;
		x:0, y: 0 &nbsp;&nbsp;|&nbsp;&nbsp;
		x:0, y: 0 &nbsp;&nbsp;|&nbsp;&nbsp;
		x:0, y: 0 &nbsp;&nbsp;|&nbsp;&nbsp;
		x:0, y: 0 &nbsp;&nbsp;|&nbsp;&nbsp;
		</span>
	</div>
</div> 
<div id="main" style="width:1024px; overflow: auto; margin: auto;">
	<div id="chart" style="margin-left:10px;width:1800px; height:300px;"></div>  
</div>
<div id="link">
	<span>
		<a href="#" onclick="goTo('stockDayDis?category=<%=cat %>');">返回</a>
	</span>
	<span>
		<a href="http://www.taifex.com.tw/chinese/9/9_7_1.asp">權重參考網址</a>
	</span>
	<span>
		<a id="getBackTest" href="#">取得回測資料</a>
	</span>
</div>
<div id="searchDiv">
	<span>Tick查詢:<input type="text" size="5" id="tickVal"/><button id="searchBtn">查詢</button></span>
</div>
<div style="margin: auto;margin-left:30px;margin-bottom: 10px;/*width: 200px;*/">
	<span id="log" style="font-size:15px;font-weight:bold;color:rgb(70%,50%,100%);">
	</span>
</div>
<div style="margin: 0px auto;">
	<table width="99%" id="mainTable">
		<tr>
			<th width="25%" id="type0"></th>
			<th width="25%" id="type1"></th>
			<th width="25%" id="type2"></th>
			<th width="25%" id="type3"></th>
		</tr>
		<tr>
			<td valign="top" align="center">
				<table id="id0" width="100%" class="dataTable">
					<thead>
					<tr>
						<th>Stock</th>
						<th>Time</th>
						<th>成交價</th>
						<th>買量</th>
						<th>賣量</th>
						<th>平均量</th>
					</tr>
					</thead>
					<tbody></tbody>
				</table>
			</td>
			<td valign="top" align="center">
				<table id="id1" width="100%" class="dataTable">
					<thead>
					<tr>
						<th>Stock</th>
						<th>Time</th>
						<th>成交價</th>
						<th>買量</th>
						<th>賣量</th>
						<th>平均量</th>
					</tr>
					</thead>
					<tbody></tbody>
				</table>
			</td>
			<td valign="top" align="center">
				<table id="id2" width="100%" class="dataTable">
					<thead>
					<tr>
						<th>Stock</th>
						<th>Time</th>
						<th>成交價</th>
						<th>買量</th>
						<th>賣量</th>
						<th>平均量</th>
					</tr>
					</thead>
					<tbody></tbody>
				</table>
			</td>
			<td valign="top" align="center">
				<table id="id3" width="100%" class="dataTable">
					<thead>
					<tr>
						<th>Stock</th>
						<th>Time</th>
						<th>成交價</th>
						<th>買量</th>
						<th>賣量</th>
						<th>平均量</th>
					</tr>
					</thead>
					<tbody></tbody>
				</table>
			</td>
		</tr>
	</table>
</div> 
<div id="backTestDiv" style="display: none;cursor: default;" align="left">
	<div style="margin:0.5em;cursor:pointer;">
		<button id="closeBtn" style="padding:0.2em">關閉</button>
		<button id="allBtn" style="padding:0.2em">全選</button>
	</div>
	<div style="padding-left: 0.5em" align="left">
		<textarea id="backTestData" readonly="readonly">
		</textarea>
	</div>
</div>
</body>
</html>